package com.tbgov.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbgov.entity.*;
import com.tbgov.entity.pojo.ResultPage;
import com.tbgov.entity.vo.FamilyList;
import com.tbgov.mapper.FamilyMapper;
import com.tbgov.mapper.FamilyMemberPovertyMapper;
import com.tbgov.service.*;
import com.tbgov.util.BaseUtil;
import com.tbgov.util.IdCardEncryptUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 家庭信息 服务实现类
 * </p>
 *
 * @author 1st
 * @since 2024-11-19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FamilyServiceImpl extends ServiceImpl<FamilyMapper, Family> implements IFamilyService {

    final FamilyMapper familyMapper;
    final IFamilyMemberService memberService;
    final IFamilyMemberPovertyService povertyService;
    final FamilyMemberPovertyMapper memberPovertyMapper;
    final IFamilyMemberGovernanceService governanceService;
    final IFamilyPovertyOptionService povertyOptionService;

    final SftpUploadService sftpUploadService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrEdit(Family family) {
        List<FamilyMember> members = family.getMembers();
        if(family.getId() != null) {
            List<Long> pIds = members.stream().map(FamilyMember::getId).filter(Objects::nonNull).toList();
            memberService.remove(Wrappers.<FamilyMember>lambdaQuery().notIn(CollectionUtils.isNotEmpty(pIds),FamilyMember::getId, pIds).eq(FamilyMember::getFamilyId, family.getId()));
        }
        saveOrUpdate(family);
        members.forEach(m -> this.addOrEdit(m.setFamilyId(family.getId()), 0));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void del(List<Long> ids) {
        List<Long> memberIds = memberService.list(Wrappers.<FamilyMember>lambdaQuery().select(FamilyMember::getId).in(FamilyMember::getFamilyId, ids)).stream().map(FamilyMember::getId).collect(Collectors.toList());
        this.delMember(memberIds);
        removeBatchByIds(ids);
    }

    @Override
    public ResultPage<FamilyList> queryFamilyList(String keyword, Integer sortType, Integer sort) {
        return ResultPage.getList(familyMapper.queryFamilyList(keyword, sortType, sort, null));
    }

    @Override
    public FamilyList queryFamilyDetail(Long id, Integer type, HttpServletRequest request) {
        FamilyList d = familyMapper.queryFamilyList(null, null, null, id).getFirst();
        if(!request.getRequestURI().contains("auth") && type == 1) {
            List<FamilyMember> list = memberService.list(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getFamilyId, id));
            list.forEach(m -> queryMemberDetail(null, m, request));
            d.setMembers(list);
        } else {
            d.setMembers(memberService.list(Wrappers.<FamilyMember>lambdaQuery().select(FamilyMember::getId, FamilyMember::getMobilePhone, FamilyMember::getName, FamilyMember::getWorkType,FamilyMember::getHealthDesc, FamilyMember::getGender, FamilyMember::getBirthday, FamilyMember::getFamilyTies).eq(FamilyMember::getFamilyId, id)));
        }
        return d;
    }

    @Override
    public FamilyMember queryMemberDetail(Long id, FamilyMember m, HttpServletRequest request) {
        FamilyMember member = Objects.nonNull(id) ?  memberService.getById(id) : m;
        id = member.getId();
        member.setPovertyList(memberPovertyMapper.queryMemberPovertys(id));
        // try {
            // 普通居民查看时不显示社会治理模块，政务人员验证通过后显示社会治理模块内容 如果没有登录信息就是没有权限查看
            // Token loginUser = TokenUtil.getLoginUser();
            member.setGovernanceList(governanceService.list(Wrappers.<FamilyMemberGovernance>lambdaQuery().eq(FamilyMemberGovernance::getMemberId, id)));
        // } catch (Exception e) {
        //     e.printStackTrace();
            // log.info("没有登录信息，无法社会治理查看");
        // }
        if (request.getRequestURI().contains("auth")) {
            member.setIdCard(IdCardEncryptUtil.hideLastFour(member.getIdCard()));
        }
        Optional.ofNullable(member.getGovernanceList()).orElseGet(ArrayList::new);
        return member;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrEdit(FamilyMember m, Integer type) {
        Integer familyTies = m.getFamilyTies();
        List<FamilyMemberPoverty> povertyList = m.getPovertyList();
        List<FamilyMemberGovernance> governanceList = m.getGovernanceList();
        if (m.getId() == null) {
            if(type == 1) {
                Assert.isTrue(familyTies == 0, "一个家庭只能只有一个户主");
            }
            memberService.save(m);
            BaseUtil.of(povertyList).ifPresent(p -> p.forEach(po -> povertyService.save(po.setMemberId(m.getId()))));
            BaseUtil.of(governanceList).ifPresent(g -> g.forEach(go -> governanceService.save(go.setMemberId(m.getId()))));
        } else {
            FamilyMember oldM = memberService.getOne(Wrappers.<FamilyMember>lambdaQuery().select(FamilyMember::getPhoto, FamilyMember::getFamilyTies).eq(FamilyMember::getId, m.getId()));
            Assert.isTrue(oldM != null, "该成员不存在，无法编辑");
            if(type == 1 && oldM.getFamilyTies() == 0) {
                Assert.isTrue(familyTies == 0, "一个家庭必须存户主");
            }
            Optional.of(oldM).map(FamilyMember::getPhoto).filter(pic -> StringUtils.isNotBlank(pic) && !pic.equals(m.getPhoto())).ifPresent(sftpUploadService::deleteFile);
            memberService.updateById(m);
            List<Long> pIds = povertyList == null ? null : povertyList.stream().map(FamilyMemberPoverty::getId).filter(Objects::nonNull).collect(Collectors.toList());
            List<Long> gIds = governanceList == null ? null : governanceList.stream().map(FamilyMemberGovernance::getId).filter(Objects::nonNull).collect(Collectors.toList());
            povertyService.remove(Wrappers.<FamilyMemberPoverty>lambdaQuery().notIn(CollectionUtils.isNotEmpty(pIds), FamilyMemberPoverty::getId, pIds).eq(FamilyMemberPoverty::getMemberId, m.getId()));
            governanceService.remove(Wrappers.<FamilyMemberGovernance>lambdaQuery().notIn(CollectionUtils.isNotEmpty(gIds), FamilyMemberGovernance::getId, gIds).eq(FamilyMemberGovernance::getMemberId, m.getId()));
            BaseUtil.of(povertyList).ifPresent(p -> p.forEach(po -> povertyService.saveOrUpdate(po.setMemberId(m.getId()))));
            BaseUtil.of(governanceList).ifPresent(g -> g.forEach(go -> governanceService.saveOrUpdate(go.setMemberId(m.getId()))));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delMember(List<Long> ids) {
        memberService.list(Wrappers.<FamilyMember>lambdaQuery().select(FamilyMember::getPhoto).in(FamilyMember::getId, ids).isNotNull(FamilyMember::getPhoto)).stream().map(FamilyMember::getPhoto).forEach(sftpUploadService::deleteFile);
        memberService.removeBatchByIds(ids);
        povertyService.remove(Wrappers.<FamilyMemberPoverty>lambdaQuery().in(FamilyMemberPoverty::getMemberId, ids));
        governanceService.remove(Wrappers.<FamilyMemberGovernance>lambdaQuery().in(FamilyMemberGovernance::getMemberId, ids));
    }

    @Override
    public List<FamilyPovertyOption> queryPovertyOptions() {
        return povertyOptionService.list();
    }
}
